//
//  AMUploadObjectTableView.m
//  AWSMobile
//
//  Created by James on 14-11-11.
//  Copyright (c) 2014年 Siemens. All rights reserved.
//

#import "AMUploadObjectTableView.h"
#import <AWSiOSSDKv2/AWSS3.h>
#import <Bolts/BFTask.h>
#import <Bolts/BFExecutor.h>

#import "AMBucketObjectCell.h"

#import "AMFunctions.h"

@interface AMUploadObjectTableView ()

@property NSString *documentPath;
@property NSMutableArray *documents;
@property NSInteger selectedRow;

@property AWSS3PutObjectRequest *putObjectRequest;

@end

@implementation AMUploadObjectTableView

- (void)viewWillAppear:(BOOL)animated
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    _documentPath = [paths objectAtIndex:0];
    _documents = [[[NSFileManager defaultManager] subpathsAtPath:_documentPath] mutableCopy];
}

- (void)viewWillDisappear:(BOOL)animated
{
    if (_putObjectRequest)
    {
        [_putObjectRequest cancel];
        _putObjectRequest = nil;
    }
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIView *view = [[UIView alloc] init];
    [self.tableView setTableFooterView:view];
    
    _documents = [[NSMutableArray alloc] initWithCapacity:1];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _documents.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"ContentCell";
    AMBucketObjectCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    id obj = _documents[indexPath.row];
    if ([obj isKindOfClass:NSClassFromString(@"NSString")])
    {
        cell.objectName.text = obj;
        cell.detailLabel.text = @"";
        if ([self checkUploadStateAtIndexPath:indexPath])
        {
            cell.detailLabel.text = @"uploaded";
        }
        
        cell.objectIndicatorColor.backgroundColor = [UIColor randomIndicatorColor];
        cell.objectIcon.image = [UIImage imageNamed:@"文件.png"];
        
        cell.indexPath = indexPath;
        cell.delegate = self;
        cell.dataSource = self;
    }
    return cell;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Alert view delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 101)
    {
        if (buttonIndex == 1)
        {
            NSString *path = [_documentPath stringByAppendingFormat:@"/%@",_documents[_selectedRow]];
            if (!_putObjectRequest)
            {
                _putObjectRequest = [[AWSS3PutObjectRequest alloc] init];
                _putObjectRequest.bucket = _bucket;
                _putObjectRequest.key = _documents[_selectedRow];
                
                NSData *data = [[NSData alloc] initWithContentsOfFile:path];
                
                _putObjectRequest.body = data;
                _putObjectRequest.contentLength = @(data.length);
            }
            [self networkStarted];
            [alertView dismissWithClickedButtonIndex:0 animated:YES];
            
            [[[AWSS3 defaultS3] putObject:_putObjectRequest] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task){
                if (!task.error) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Upload success" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                    alert.tag = 102;
                    [alert show];
                }
                else
                {
                    NSLog(@"%@",task.error);
                }
                return nil;
            }];
        }
    }
    else if (alertView.tag == 102)
    {
        [self networkStopped];
    }
    
}
#pragma mark - Actions
- (void)networkStarted
{
    UIActivityIndicatorView *iView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    UIBarButtonItem *iBarItem = [[UIBarButtonItem alloc] initWithCustomView:iView];
    [iView startAnimating];
    self.navigationItem.rightBarButtonItem = iBarItem;
}

- (void)networkStopped
{
    self.navigationItem.rightBarButtonItem = nil;
    [self cancel:nil];
}

- (BOOL)checkUploadStateAtIndexPath:(NSIndexPath *)indexPath
{
    id obj = _documents[indexPath.row];
    if (_existContents && [obj isKindOfClass:NSClassFromString(@"NSString")])
    {
        for (AWSS3Object *aObject in _existContents)
        {
            if ([aObject.key isEqualToString:obj])
            {
                return YES;
            }
        }
    }
   return NO;
}

- (IBAction)cancel:(UIBarButtonItem *)sender
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - DNS cell data source
- (NSInteger)numberOfButtonsInSwipeableCellAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self checkUploadStateAtIndexPath:indexPath])
    {
        return 1;
    }
    return 2;
}

- (NSString *)titleForButtonAtIndex:(NSInteger)index inCellAtIndexPath:(NSIndexPath *)indexPath
{
    return @"";
}

- (UIImage *)imageForButtonAtIndex:(NSInteger)index inCellAtIndexPath:(NSIndexPath *)indexPath
{
    if (index == 0)
    {
        return [UIImage imageNamed:@"delete_object"];
    }
    
    return [UIImage imageNamed:@"upload_object"];
}

- (UIColor *)textColorForButtonAtIndex:(NSInteger)index inCellAtIndexPath:(NSIndexPath *)indexPath
{
    return [UIColor whiteColor];
}

- (UIColor *)backgroundColorForButtonAtIndex:(NSInteger)index inCellAtIndexPath:(NSIndexPath *)indexPath
{
    if (index == 0)
    {
        return [UIColor colorWithHexString:@"f26c6c"];
    }
    return [UIColor colorWithHexString:@"97c2b3"];
}

#pragma mark - DNS cell delegate
- (void)swipeableCell:(AMBucketObjectCell *)cell didSelectButtonAtIndex:(NSInteger)index
{
    [cell closeCell:YES];
    if (index == 0)
    {
        NSString *path = [_documentPath stringByAppendingFormat:@"/%@",cell.objectName.text];
        NSError *error;
        [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        if (!error)
        {
            [_documents removeObjectAtIndex:cell.indexPath.row];
            [self.tableView deleteRowsAtIndexPaths:@[cell.indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        
    }
    else if (index == 1)
    {
        _selectedRow = cell.indexPath.row;
        NSString *promptMessage = [NSString stringWithFormat:@"Upload %@ to %@",cell.objectName.text,_bucket];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Upload" message:promptMessage delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
        alert.tag = 101;
        [alert show];
    }
}

- (void)swipeableCellDidClose:(DNSSwipeableCell *)cell
{
    
}

- (void)swipeableCellDidOpen:(DNSSwipeableCell *)cell
{
    
}

@end
